/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.constant.PunishMainServicePortUriConstant;
import com.icinfo.cloud.provider.common.dto.SendDocumentDto;
import com.icinfo.cloud.provider.common.enums.ApiVisitDataSourceEnum;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.HeaderUtil;
import com.icinfo.cloud.provider.common.utils.ImageUtil;
import com.icinfo.cloud.provider.common.utils.PunishMainClientUtil;
import com.icinfo.cloud.provider.exception.BusinessException;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.*;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.vo.DocumentCommonFormHtmlVo;
import com.icinfo.cloud.provider.punish.common.electricsent.dto.*;
import com.icinfo.cloud.provider.punish.common.electricsent.enums.DocumentSendStatusEnum;
import com.icinfo.cloud.provider.punish.common.electricsent.enums.RealPlaceSentTypeEnum;
import com.icinfo.cloud.provider.punish.common.electricsent.enums.SendWayEnum;
import com.icinfo.cloud.provider.punish.common.electricsent.enums.SentRegisterReceiverTypeEnum;
import com.icinfo.cloud.provider.punish.common.electricsent.model.DocumentSendRecord;
import com.icinfo.cloud.provider.punish.common.electricsent.vo.CaseDocumentSendinfoConfirmVo;
import com.icinfo.cloud.provider.punish.common.electricsent.vo.DocumentSendRecordByPartiesVo;
import com.icinfo.cloud.provider.punish.common.electricsent.vo.DocumentSentRegisterVo;
import com.icinfo.cloud.provider.punish.common.seal.dto.FileSealInfoQueryDto;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.dto.*;
import com.icinfo.cloud.provider.punish.mapper.*;
import com.icinfo.cloud.provider.punish.service.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseDocumentRecordDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.DocumentKeyInfoRequest;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.HandleTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartiesReasonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartyTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseDocumentKeyInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseDocumentRecordVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesRecordVo;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.model.CaseDocumentSendinfoConfirm;
import com.icinfo.cloud.provider.punish.vo.AppDocumentSentFlowDetailInfoVo;
import com.icinfo.cloud.provider.punish.vo.CasePartiesDocSendInfoVo;
import com.icinfo.cloud.provider.punish.vo.SendTaskVo;
import com.icinfo.cloud.provider.punish.vo.SentFormInfoVo;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述: 文书发送记录 document_send_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年03月30日
 */
@Service
@Slf4j
public class DocumentSendRecordServiceImpl extends MyBatisServiceSupport implements IDocumentSendRecordService {

    @Resource
    private DocumentSendRecordMapper documentSendRecordMapper;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Resource
    private CasePartiesLegalInfoMapper casePartiesLegalInfoMapper;
    @Resource
    private CasePartiesPersonInfoMapper casePartiesPersonInfoMapper;
    @Resource
    SysDepartParamMapper sysDepartParamMapper;
    /*@Resource
    private CaseMainInfoClient caseMainInfoClient;
    @Resource
    private CasePartiesRecordClient casePartiesRecordClient;
    @Resource
    private CaseDocumentRecordClient caseDocumentRecordClient;
    @Resource
    private StageDocCommonOperateClient stageDocCommonOperateClient;
    @Resource
    private DocumentSentFlowClient documentSentFlowClient;
    @Resource
    private ConfigBusiParamDocumentInfoClient configBusiParamDocumentInfoClient;*/
    @Resource
    ConfigBusiParamDocumentInfoMapper configBusiParamDocumentInfoMapper;
    @Resource
    private IAppCaseBeforeDocumentRecordService appCaseBeforeDocumentRecordService;
    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private CaseDocumentSendinfoConfirmMapper caseDocumentSendinfoConfirmMapper;
    @Resource
    private AppCaseBeforeDocumentRecordMapper appCaseBeforeDocumentRecordMapper;

    @Resource
    private AppDocumentInfoDetailMapper appDocumentInfoDetailMapper;

    @Resource
    private CaseDocumentNumberSerialMapper caseDocumentNumberSerialMapper;

    @Resource
    private AppDocumentRelatedGoodsMapper appDocumentRelatedGoodsMapper;

    @Resource
    private ConfigBusiParamDocumentColumnMapper configBusiParamDocumentColumnMapper;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private CaseReasonMainRecordMapper caseReasonMainRecordMapper;
    @Resource
    CaseHandlePersonRecordMapper caseHandlePersonRecordMapper;
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    private ISysDepartParamService sysDepartParamService;

    @Value("${tzService.url}")
    private String url;

    /**
     * 获取待发送文书记录数量
     * @author   lxj
     * @param   userId
     * @return int
     */
    @Override
    public int countWaitSendDocument(String userId) {
        UserDTO userDTO = UserUtil.getUserInfo();
        int count =  documentSendRecordMapper.countWaitSend(userId, userDTO.getOrgCode());
        return count;
    }

    /**
     * 获取待发送文书记录
     * @author   lxj
     * @param   documentSendDto
     * @return List
     */
    @Override
    public List<SendTaskVo> getDocumentSendList(DocumentSendDto documentSendDto) {
        PageHelper.startPage(documentSendDto.getPageNum(), documentSendDto.getLength());
        String sendStatus = documentSendDto.getSendStatus();
        if(!DocumentSendStatusEnum.isLegalEnumCode(sendStatus)){
            throw new BusinessException("请指定有效的发送状态");
        }
        List<SendTaskVo> list;
        if (DocumentSendStatusEnum.SEND_SUCCESS.getCode().equals(sendStatus)) {
            list = documentSendRecordMapper.getDocumentSentList(documentSendDto);
        }else {
            list = documentSendRecordMapper.getDocumentSendList(documentSendDto);
        }
        //未送达计算剩余时间---sendTime 比较
        for (int i = 0; i < list.size(); i++) {
            SendTaskVo vo = list.get(i);

            String documentId = vo.getDocumentId();
            List<CasePartiesRecordVo> casePartiesInfoList = casePartiesRecordService.getCasePartiesInfo(vo.getCaseId());
            CasePartiesRecordVo theFirstPartyInfo = casePartiesInfoList.get(Constant.INTEGER_0);
            String partyShowName = theFirstPartyInfo.getPartyName();
            if (casePartiesInfoList.size() > 1) {
                //多当事人合并处罚对当事人名称进行处理
                if (HandleTypeEnum.MERGE_PUNISH.getCode().equals(vo.getHandleType())) {
                    int partyNum = casePartiesInfoList.size();
                    if(partyNum > 1){
                        partyShowName += "等"+partyNum+"个";
                    }
                } else {
                    for (CasePartiesRecordVo casePartiesRecordVo : casePartiesInfoList) {
                        if (vo.getPartyId().equals(casePartiesRecordVo.getPartyId())) {
                            partyShowName = casePartiesRecordVo.getPartyName();
                            break;
                        }
                    }
                }
            }

            vo.setPartyName(partyShowName);
            vo.setPartyType(theFirstPartyInfo.getPartyType());

            if(vo.getSentDeadline()!=null){
                String time = BaseUtil.calTime(new Date(),vo.getSentDeadline(),"true");
                vo.setRemainTime(time);
            }
            vo.setSentWay(SendWayEnum.getValueByCode(vo.getSentWay()));

            //送达成功,查询送达记录表获取送达方式
            if (DocumentSendStatusEnum.SEND_SUCCESS.getCode().equals(sendStatus)) {
                //查询是否有电子送达
                DocumentSendRecordQueryDto queryDto = new DocumentSendRecordQueryDto();
                queryDto.setCaseId(vo.getCaseId());
                queryDto.setDocumentId(vo.getDocumentId());
                queryDto.setIsSendSuccess(DocumentSendStatusEnum.SEND_SUCCESS.getCode());
                if (HandleTypeEnum.PART_PUNISH.getCode().equals(vo.getHandleType())) {
                    queryDto.setPartyId(vo.getPartyId());
                }
                List<DocumentSendRecord> documentSendRecordList = getDocumentSendRecordList(queryDto);
                for (DocumentSendRecord e : documentSendRecordList) {
                    if (SendWayEnum.TEXT_MSG.getCode().equals(e.getSentWay())) {
                        vo.setSentWay(SendWayEnum.getValueByCode(e.getSentWay()));
                        break;
                    }
                }

                //电子送达
                if (!ObjectUtils.isEmpty(vo.getSentWay())) continue;

                //其他送达方式
                if (!ObjectUtils.isEmpty(documentSendRecordList)) {
                    vo.setSentWay(SendWayEnum.getValueByCode(documentSendRecordList.get(0).getSentWay()));
                    continue;
                }


                //送达回证
                ConfigBusiParamDocumentInfo sdhzConfig = configBusiParamDocumentInfoService.getSDHZDetailBySentDocumentCatalogCode(vo.getDocumentCatalogCode());
                String sentReceiptPrintDocumentCatalogCode = sdhzConfig.getDocumentCatalogCode();
                if(!ObjectUtils.isEmpty(sentReceiptPrintDocumentCatalogCode)) {
                    CaseDocumentRecord sentReceiptDocInfo = caseDocumentRecordService.getCaseDocumentRecord(vo.getCaseId(), sentReceiptPrintDocumentCatalogCode, vo.getPartyId());
                    if(!ObjectUtils.isEmpty(sentReceiptDocInfo)) {
                        documentId = sentReceiptDocInfo.getId();
                    }
                }

                queryDto.setDocumentId(documentId);
                documentSendRecordList = getDocumentSendRecordList(queryDto);
                if (!ObjectUtils.isEmpty(documentSendRecordList)) {
                    vo.setSentWay(SendWayEnum.getValueByCode(documentSendRecordList.get(0).getSentWay()));
                }

            }
        }
        return list;
    }

    /**
     * 送达记录查询
     *
     * @param queryDto
     * @return
     */
    public List<DocumentSendRecord> getDocumentSendRecordList(DocumentSendRecordQueryDto queryDto) {
        Example example = new Example(DocumentSendRecord.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("caseId", queryDto.getCaseId()).andEqualTo("isDelete", "0")
                .andEqualTo("documentId", queryDto.getDocumentId());
        if (!ObjectUtils.isEmpty(queryDto.getPartyId())) {
            criteria.andEqualTo("partyId", queryDto.getPartyId());
        }
        example.orderBy("sentTime").asc();
        List<DocumentSendRecord> documentSendRecords = documentSendRecordMapper.selectByExample(example);
        return documentSendRecords;
    }

    /**
     * 获取DocumentSendRecord
     * @param caseId
     * @param documentId
     * @param partyId 当事人id
     * @return  DocumentSendRecord
     */
    private DocumentSendRecord getDocSend(String caseId, String documentId, String partyId) {
        Example example = new Example(DocumentSendRecord.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("caseId", caseId).andEqualTo("isDelete", "0")
                .andEqualTo("documentId", documentId);
        if (!ObjectUtil.isEmpty(partyId)) {
            criteria.andEqualTo("partyId", partyId);
        }
        List<DocumentSendRecord> list = documentSendRecordMapper.selectByExample(example);
        if (ObjectUtil.isEmpty(list) || list.size() == 0) {
            return null;
        }
        return list.get(0);
    }
    /**
     * 生成签字捺印文书
     * @author   lxj
     * @param appDocumentSignSaveDto
     * @return  String
     */
    @Override
    public String submitSendFingerAndSign(AppDocumentSignSaveDto appDocumentSignSaveDto) {
        String caseId = appDocumentSignSaveDto.getCaseId();
        String partyId = appDocumentSignSaveDto.getPartyId();
        String documentCatalogCode = appDocumentSignSaveDto.getDocumentCatalogCode();
        String documentId = appDocumentSignSaveDto.getDocumentId();

        if(!ObjectUtils.isEmpty(caseId)){
            Map<String, Object> paramMap = Collections.singletonMap("caseId", caseId);
            Result<Boolean> checkResult = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.VALIDATE_CASE_IS_IN_NOT_DEAL_STATUS, "", paramMap);
            //Result<Boolean> checkResult = caseMainInfoClient.validateCaseIsInNotDealStatus(caseId);
            if (checkResult.getData()) {
                throw new com.icinfo.cloud.provider.common.exception.BusinessException("当前案件状态不允许进行该操作");
            }

            Result<JSONObject> caseMainInfoResult = PunishMainClientUtil.httpGet(PunishMainServicePortUriConstant.GET_CASE_MAIN_INFO, paramMap);
            //Result<CaseMainInfoVo> caseMainInfoResult = caseMainInfoClient.getCaseMainInfo(caseId);
            CaseMainInfoVo caseMainInfo;
            if (!ObjectUtil.isEmpty(caseMainInfoResult)) {
                caseMainInfo = JSONObject.parseObject(caseMainInfoResult.getData().toJSONString(), CaseMainInfoVo.class);
            } else {
                throw new BusinessException("getLocaleSend-getCaseMainInfo response null");
            }
            String casePartiesReasonType = caseMainInfo.getCasePartiesReasonType();
            if (ObjectUtils.isEmpty(partyId)) {
                if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)) {
                    throw new com.icinfo.cloud.provider.common.exception.BusinessException("多当事人时送达流程指定当事人id");
                }
            }
        }
        //生成签字后的文书
        StageDocCommonOperateSaveDto saveDto =  new StageDocCommonOperateSaveDto();
        saveDto.setCaseId(caseId);
        //送达回证的文书目录编码
        Result<JSONObject> configBusiParamDocumentInfoResult = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_DETAIL_BY_DOCUMENT_CATALOG_CODE + "/" + documentCatalogCode, "");
        //Result<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfoResult = configBusiParamDocumentInfoClient.getDetailByDocumentCatalogCode(documentCatalogCode);
        if (!ObjectUtil.isEmpty(configBusiParamDocumentInfoResult)) {
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = JSONObject.parseObject(configBusiParamDocumentInfoResult.getData().toJSONString(), ConfigBusiParamDocumentInfo.class);
            if (!ObjectUtil.isEmpty(configBusiParamDocumentInfo)) {
                String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
                String sentReceiptPrintDocumentCatalogCode = "";
                if (Constant.STRING_KIND_CODE_CFJDS.equals(documentKindCode)) {
                    sentReceiptPrintDocumentCatalogCode = "CFJDSPBFC20F_SDHZBD1F7";
                } else if ("CFGZS".equals(documentKindCode)) {
                    sentReceiptPrintDocumentCatalogCode = "CFGZSPB7B30D_SDHZBD1F5";
                } else if ("CFGZSTZL".equals(documentKindCode)) {
                    sentReceiptPrintDocumentCatalogCode = "CFGZSPB7B30D_SDHZBD1F6";
                } else if ("BYCFJDS".equals(documentKindCode)) {
                    sentReceiptPrintDocumentCatalogCode = "BYCFJDSPB4FF3E_SDHZ7B444";
                } else if ("JDYJGZS".equals(documentKindCode)) {
                    sentReceiptPrintDocumentCatalogCode = "JDYJGZS_SDHZC8650";
                } else if (DocumentKindEnum.DOC_KIND_XZJDLXCGS.getCode().equals(documentKindCode)) {
                    sentReceiptPrintDocumentCatalogCode = "XZJDLXCGSD6EF7_SDHZBD3FG";
                }

                DocumentKeyInfoRequest request = new DocumentKeyInfoRequest();
                request.setDocumentCatalogCode(sentReceiptPrintDocumentCatalogCode);
                request.setCaseId(caseId);
                request.setPartyId(partyId);
                Result<JSONObject> documentKeyInfo = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_DOCUMENT_KEY_INFO_BY_SPECIAL_CONDITION, request);
                //Result<CaseDocumentKeyInfoVo> documentKeyInfo = caseDocumentRecordClient.getDocumentKeyInfoBySpecialCondition(request);
                CaseDocumentKeyInfoVo record = JSONObject.parseObject(documentKeyInfo.getData().toJSONString(), CaseDocumentKeyInfoVo.class);
                if(ObjectUtil.isEmpty(record)){
                    //获取签完字的送达回证地址
                    return record.getDocumentUrlAfterSign();
                }

            }
        }
        return null;
    }

    /**获取文书抬头
     *
     * @return
     */
    @Override
    public String getStandOrgName(){
        UserDTO userDTO = UserUtil.getUserInfo();
       /* Example example = new Example(SysDepartParam.class);
        example.createCriteria().andEqualTo("orgCode",userDTO.getOrgCode());
        List<SysDepartParam> list = sysDepartParamMapper.selectByExample(example);
        if(list!=null&&list.size()>0){
           return list.get(0).getOrgStandardName();
        }*/
        SysDepartParam sysDepartParam=sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(userDTO.getOrgCode(),userDTO.getDeptCode());
        if(null!=sysDepartParam){
            return sysDepartParam.getOrgStandardName();
        }
        return  null;
    }
    /**获取文书抬头
     *
     * @return
     */
    @Override
    public String getStandOrgNameByCondition(String orgCode,String deptCode){
        SysDepartParam sysDepartParam=sysDepartParamService.getPublicSecurityEntrustSysDepartParamByOrgCodeAndDeptCode(orgCode,deptCode);
        if(null!=sysDepartParam){
            return sysDepartParam.getOrgStandardName();
        }
        return  null;
    }
    /**获取文书种类
     *
     * @return
     */
    private String getDocName(String cateLogCode){
        Example example = new Example(ConfigBusiParamDocumentInfo.class);
        example.createCriteria().andEqualTo("documentCatalogCode",cateLogCode).andEqualTo("isDeleted","0");
        List<ConfigBusiParamDocumentInfo> list = configBusiParamDocumentInfoMapper.selectByExample(example);
        if(list!=null&&list.size()>0){
            return list.get(0).getDocumentKindName();
        }
        return null;
    }

    /**
     * 获取空白文书地址
     * @param sendDocumentDto
     * @param sendType
     * @param documentCatalogCode
     * @return
     */
    private String getDocUrl(SendDocumentDto sendDocumentDto,String sendType,String documentCatalogCode,String partyId){

        Map<String, String> headers = HeaderUtil.headerInfo();
        StageDocCommonOperateSaveDto saveDto=  new StageDocCommonOperateSaveDto();
        saveDto.setCaseId(sendDocumentDto.getCaseId());

        saveDto.setDocumentCatalogCode(documentCatalogCode);
        saveDto.setBelongDocumentId(sendDocumentDto.getDocumentId());
        //是否生成空白文档，1.是（不盖章）
        saveDto.setIsGetBlankDoc("1");
        saveDto.setIsUpdateRelationTable("0");

        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(sendDocumentDto.getDocumentId());
        DocumentSendRecord send = getDocSend(caseDocumentRecord.getCaseId(),caseDocumentRecord.getId(),partyId);
        HashMap<String ,Object> map = new HashMap<>();
        map.put("SDHZ_SDDD",send.getReceiverAccount());
        map.put("SDHZ_SDSJ",BaseUtil.localDateTimeToFormatStr(send.getSentTime()));
        map.put("SDHZ_SDFS",sendType);
        map.put("SDHZ_SDGX",sendDocumentDto.getReceiverRelation());
        map.put("SDHZ_BADW",getStandOrgName());
        map.put("SDHZ_SSDR",send.getReceiverName());
        String kindName = getDocName(caseDocumentRecord.getDocumentCatalogCode());
        map.put("SDHZ_WSMC",kindName);
        //送达文书文号
        map.put("SDHZ_WSWH",kindName+"，"+caseDocumentRecord.getDocumentNumber());
        saveDto.setDataMap(map);
        String param = JSON.toJSONString(saveDto);
        String response = HttpUtil.createPost(url.concat("punish/stagedoc/common/saveDocInfo")).addHeaders(headers).body(param).execute().body();
        Result<String> result = JSON.parseObject(response, Result.class);
        if(result.getCode()==200){
            CaseDocumentRecord record = caseDocumentRecordMapper.selectByPrimaryKey(sendDocumentDto.getDocumentId());
            return record.getDocumentUrl();
        }
        return null;
    }

    /**
     * 送达后文书详情---url
     * @param documentId
     * @author lxj
     * @return
     */
    @Override
    public String  getDocSentDetail(String documentId) {
        CaseDocumentRecord record = caseDocumentRecordMapper.selectByPrimaryKey(documentId);
        if(record!=null){
            if (StringUtils.isNotEmpty(record.getDocumentUrlAfterSeal())) {
                return record.getDocumentUrlAfterSeal();
            }else if (StringUtils.isNotEmpty(record.getDocumentUrlAfterSign())) {
                return record.getDocumentUrlAfterSign();
            }
            return record.getDocumentUrl();
        }
        return "";
    }

    @Override
    public DocumentCommonFormHtmlVo getDocumentFormHtml(StageDocCommonHtmlRequest request) {
        String param = JSON.toJSONString(request);
        String response = HttpUtil.createPost(url.concat("punish/stagedoc/common/getDocBaseInfo")).body(param).execute().body();
        if (StringUtils.isNotEmpty(response)) {
            JSONObject obj = JSONObject.parseObject(response);
            if (obj.getIntValue("code") == 200) {
                if (obj.getJSONObject("data") != null) {
                    DocumentCommonFormHtmlVo result = JSON.parseObject(obj.getString("data"), DocumentCommonFormHtmlVo.class);
                    return result;
                }
            }
        }
        return null;
    }


    /**
     * 描述：生成送达回证文书
     *
     * @param dto {@link StageDocCommonOperateSaveDto}
     * @return String 送达回证文书地址
     * @author xiangyuyu
     * @date 2022-06-27 16:00
     */
    @Override
    public String generateSentReceiptDoc(StageDocCommonOperateSaveDto dto){
        PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.SAVE_DOC_INFO, dto);
        //stageDocCommonOperateClient.saveDocInfo(dto);
        DocumentKeyInfoRequest request = new DocumentKeyInfoRequest();
        BeanUtils.copyProperties(dto,request);
        Result<JSONObject> documentKeyInfo = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_DOCUMENT_KEY_INFO_BY_SPECIAL_CONDITION, request);
        //Result<CaseDocumentKeyInfoVo> documentKeyInfo = caseDocumentRecordClient.getDocumentKeyInfoBySpecialCondition(request);
        CaseDocumentKeyInfoVo record = JSONObject.parseObject(documentKeyInfo.getData().toJSONString(), CaseDocumentKeyInfoVo.class);

        if(!ObjectUtil.isEmpty(record)){
            // FIXME: 2022/6/27 是否需要根据入参获取不同文书地址
            return record.getDocumentUrl();
        }
        return null;
    }


    /**
     * 确认送达(电子送达)
     *
     * @param saveDto
     * @return
     */
    @Override
    public Result<String> confirmSend(ConfirmSendSaveDto saveDto) {
        saveDto.setDataSource(ApiVisitDataSourceEnum.PUNISH_MOBILE.getId());
        return PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.CONFIRM_SEND, saveDto);
    }

    /**
     * 描述： 发送文书短信
     *
     * @author: zhengqiang
     * @date: 2022/8/28
     * @param: smsDto
     * @return {@link Result< String>}
     **/
    @Override
    public Result<String> sendDocumentSms(SendDocumentSmsDto smsDto) {
        return PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.SEND_DOCUMENT_SMS, smsDto);
    }

    @Override
    public Result<String> saveDocumentSignIdInfo(AppDocumentSignFileAssembleInfoDto saveDto) {
        String documentId = saveDto.getDocumentId();
        String sentWay = saveDto.getSendWay();
        String realPlaceSentType = saveDto.getRealPlaceSentType();
        //如果是移动端+当场送达+源文件送达 需要进行一次"待确认"标记
        RealPlaceSentInfoSaveDto realPlaceSentInfoSaveDto = new RealPlaceSentInfoSaveDto();
        realPlaceSentInfoSaveDto.setDocumentId(documentId);
        //现场送达方式（1-原件签收/2-送达回证）
        realPlaceSentInfoSaveDto.setRealPlaceSentType(realPlaceSentType);
        realPlaceSentInfoSaveDto.setPartyId(saveDto.getPartyId());
        realPlaceSentInfoSaveDto.setDataSource(ApiVisitDataSourceEnum.PUNISH_MOBILE.getId());
        realPlaceSentInfoSaveDto.setSentWay(sentWay);
        if(RealPlaceSentTypeEnum.YJQS.getCode().equals(realPlaceSentType) && SendWayEnum.LOCAL_MSG.getCode().equals(sentWay)){
            //现场送达状态（0-待确认/1-已确认/2-取消）
            realPlaceSentInfoSaveDto.setRealPlaceSentStatus(Constant.STRING_0);
            signRealPlaceSentInfo(realPlaceSentInfoSaveDto);
        }

        String caseId = saveDto.getCaseId();
        String partyId = saveDto.getPartyId();
        //step1:重新生成签字捺印后的文书
        //获取文书信息
        CaseDocumentRecordVo caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecordInfo(documentId);
        String documentCatalogCode = caseDocumentRecord.getDocumentCatalogCode();
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo
                = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        if(YesOrNoEnum.YES.getCode().equals(saveDto.getIsSignSentReceipt())){
            //获取送达回证的文书目录编码
            //送达回证
            ConfigBusiParamDocumentInfo sdhzConfig = configBusiParamDocumentInfoService.getSDHZDetailBySentDocumentCatalogCode(documentCatalogCode);
            String sentReceiptPrintDocumentCatalogCode = sdhzConfig.getDocumentCatalogCode();
            if (ObjectUtils.isEmpty(sentReceiptPrintDocumentCatalogCode)) {
                return Result.error("未匹配到送达文书对应送达回证文书目录编码配置信息");
            }
            documentCatalogCode = sentReceiptPrintDocumentCatalogCode;
            //获取送达回证文书记录信息
            CaseDocumentRecordDto caseDocumentRecordDto = new CaseDocumentRecordDto();
            caseDocumentRecordDto.setCaseId(caseId);
            caseDocumentRecordDto.setDocumentCatalogCode(sentReceiptPrintDocumentCatalogCode);
            caseDocumentRecordDto.setPartyId(partyId);
            Result<JSONObject> documentRecordResult = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_CASE_DOCUMENT_RECORD, caseDocumentRecordDto);
            if(!ObjectUtils.isEmpty(documentRecordResult)){
                int code = documentRecordResult.getCode();
                if(HttpStatus.HTTP_OK == code){
                    CaseDocumentRecord record = JSONObject.parseObject(documentRecordResult.getData().toJSONString(), CaseDocumentRecord.class);
                    caseDocumentRecord = new CaseDocumentRecordVo();
                    BeanUtils.copyProperties(record,caseDocumentRecord);
                } else {
                    return Result.error(documentRecordResult.getMessage());
                }
            } else {
                return Result.error("未匹配到送达回证的文书信息");
            }
        }
        if (Constant.STRING_KIND_CODE_SDDZQRS.equals(documentKindCode)) {
            //送达地址确认书确认时更新送达地址确认书表的状态为1
            Example updateExample = new Example(CaseDocumentSendinfoConfirm.class);
            updateExample.createCriteria().andEqualTo("caseId", caseDocumentRecord.getCaseId()).andEqualTo("partyId", caseDocumentRecord.getPartyId());
            CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm = new CaseDocumentSendinfoConfirm();
            caseDocumentSendinfoConfirm.setStatus(Constant.INTEGER_1);
            caseDocumentSendinfoConfirmMapper.updateByExampleSelective(caseDocumentSendinfoConfirm, updateExample);
        }

//        JSONObject documentContentJson = JSON.parseObject(caseDocumentRecord.getDocumentContent());
        //签名base64优化成地址 20230522
//        String base64Str = ImageUtil.overlapImage(saveDto.getSignFile(), saveDto.getFingerprint());
        // todo 修改签名文件获取地址
        String signFile = appCaseBeforeDocumentRecordService.getFileByteByFileId(saveDto.getFileId());
        saveDto.setSignFile(signFile);
        String ossUrl = appCaseBeforeDocumentRecordService.base64PdfToOssUrl(signFile);
//        documentContentJson.put("signFingerprintPic", ossUrl);
//        documentContentJson.put("signFingerprintDate", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
//        if (YesOrNoEnum.YES.getCode().equals(saveDto.getIsSignSentReceipt())) {
//            documentContentJson.put("SDHZ_SJR_QM", !ObjectUtils.isEmpty(saveDto.getSignFile()) ? saveDto.getSignFile() : "");
//            documentContentJson.put("signFingerprintPic", !ObjectUtils.isEmpty(saveDto.getFingerprint()) ? saveDto.getFingerprint() : "");
//            documentContentJson.put("SDHZ_JZRQMSJ", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
//        }
//
//        String documentContent = documentContentJson.toJSONString();
//
//        // 重新生成文书
//        Map<String, Object> jsonObject = JSON.parseObject(documentContent);
//        TemplateCodeInfoDto dto = new TemplateCodeInfoDto(documentCatalogCode,caseId,jsonObject);
//        Result<String> templateCodeResult = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_TEMPLATE_CODE_BY_DOCUMENT_CATALOG_CODE, dto);
//        int code = templateCodeResult.getCode();
//        String templateCode;
//        if(HttpStatus.HTTP_OK == code ){
//            templateCode = templateCodeResult.getData();
//        } else {
//            return Result.error(templateCodeResult.getMessage());
//        }
//        FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
//        pdfRequest.setTemplateCode(templateCode);
//        pdfRequest.setParamMap(jsonObject);
//        pdfRequest.setIsGeneratePcDoc(YesOrNoEnum.YES.getCode());
//        //fixme 后期统一调用pc端接口
//        Map<String, String> unSealPdfUrl = appCaseBeforeDocumentRecordService.getConvertedPdfUrl(pdfRequest);
//        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseDocumentRecord.getCaseId());
//        SysDepartParam sysDepartParam= sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
//
//        FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
//        queryDto.setFileBase64(unSealPdfUrl.get("fileBase64"));
//        queryDto.setUniscid(sysDepartParam.getUnicode());
//        queryDto.setDeptCode(caseMainInfo.getCaseDeptCode());
//        String pdfSealUrl = appCaseBeforeDocumentRecordService.dealFileSeal(queryDto);
        // 签章的地址
        String pdfSealUrl = ossUrl;

        //保存文书签字捺印字段
        CaseDocumentRecord sdhzCaseDocumentRecord = new CaseDocumentRecord();
        sdhzCaseDocumentRecord.setId(caseDocumentRecord.getId());
        sdhzCaseDocumentRecord.setDocumentUrlAfterSign(pdfSealUrl);
        caseDocumentRecordMapper.updateByPrimaryKeySelective(sdhzCaseDocumentRecord);

        //step2:标记文书【已确认（已送达）】
        //标记
        realPlaceSentInfoSaveDto.setRealPlaceSentStatus(Constant.STRING_1);
        Result<String> result = signRealPlaceSentInfo(realPlaceSentInfoSaveDto);
        if (!ObjectUtils.isEmpty(result)) {
            if (HttpStatus.HTTP_OK == result.getCode()) {
                return Result.success(Constant.STRING_OPERATE_SUCCESS);
            } else {
                return Result.error(Constant.STRING_OPERATE_FAIL + ":" + result.getMessage());
            }
        }
        return Result.error(Constant.STRING_OPERATE_FAIL);
    }

    /**
     * 描述：【V1.3.2】描述：现场送达状态标记
     *
     * @param saveDto {@link RealPlaceSentInfoSaveDto}
     * @return Result<String> 操作结果
     * @author xiangyuyu
     * @date 2022/8/5
     * @since 1.3.2
     */
    @Override
    public Result<String> signRealPlaceSentInfo(RealPlaceSentInfoSaveDto saveDto) {
        saveDto.setDataSource(ApiVisitDataSourceEnum.PUNISH_MOBILE.getId());
        return PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.SIGN_REAL_PLACE_SENT_INFO, saveDto);
    }

    /**
     * 描述：【V1.3.2】保存文书送达登记
     *
     * @param saveDto {@link DocumentSentRegisterSaveDto}
     * @return {@link Result <String>} 保存结果
     * @author xiangyuyu
     * @date 2022/8/5
     * @since 1.3.2
     */
    @Override
    public Result<String> saveDocumentSentRegister(DocumentSentRegisterSaveDto saveDto) {
        saveDto.setDataSource(ApiVisitDataSourceEnum.PUNISH_MOBILE.getId());
        saveDto.setIsUpdateRelationTable(YesOrNoEnum.NO.getCode());
        saveDto.setDataSource(ApiVisitDataSourceEnum.PUNISH_MOBILE.getId());
        Result<String> result = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.SAVE_DOCUMENT_SENT_REGISTER, saveDto);
        if(!ObjectUtils.isEmpty(result)){
            int code = result.getCode();
            if(HttpStatus.HTTP_OK != code){
                return Result.error(result.getMessage());
            }
        }
        String documentId = saveDto.getDocumentId();
        RealPlaceSentInfoSaveDto realPlaceSentInfoSaveDto = new RealPlaceSentInfoSaveDto();
        realPlaceSentInfoSaveDto.setDocumentId(documentId);
        String realPlaceSentType = RealPlaceSentTypeEnum.SDHZ.getCode();
        //现场送达方式（1-原件签收/2-送达回证）
        realPlaceSentInfoSaveDto.setRealPlaceSentType(realPlaceSentType);
        realPlaceSentInfoSaveDto.setPartyId(saveDto.getPartyId());
        //现场送达状态（0-待确认/1-已确认/2-取消）
        realPlaceSentInfoSaveDto.setRealPlaceSentStatus(Constant.STRING_0);
        realPlaceSentInfoSaveDto.setDataSource(ApiVisitDataSourceEnum.PUNISH_MOBILE.getId());
        realPlaceSentInfoSaveDto.setSentWay(saveDto.getSentWay());
        signRealPlaceSentInfo(realPlaceSentInfoSaveDto);
        return Result.success(Constant.STRING_OPERATE_SUCCESS);
    }

    /**
     * 描述： 根据案件信息查询文书送达地址确认书信息
     *
     * @author: zhengqiang
     * @date: 2022/6/30
     * @param: request
     * @return {@link CaseDocumentSendinfoConfirmVo}
     **/
    @Override
    public CaseDocumentSendinfoConfirmVo getCaseDocumentSendInfoConfirmInfo(DocumentSentAddressInfoRequest request) {
        Result<JSONObject> result = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_RECEIVER_INIT_INFO, request);
        CaseDocumentSendinfoConfirmVo vo = new CaseDocumentSendinfoConfirmVo();
        if(!ObjectUtils.isEmpty(result)){
            int code = result.getCode();
            if(HttpStatus.HTTP_OK != code){
                throw new BusinessException(result.getMessage());
            } else {
                vo = JSONObject.parseObject(result.getData().toJSONString(), CaseDocumentSendinfoConfirmVo.class);
            }
        }
        /*String caseId = request.getCaseId();
        if (ObjectUtils.isEmpty(caseId)) {
            throw new com.icinfo.cloud.provider.common.exception.BusinessException("未指定案件id");
        }

        //查询案件部门编码
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        String deptCode = caseMainInfo.getCaseDeptCode();

        Example queryExample = new Example(CasePartiesRecord.class);
        queryExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status", "1");
        List<CasePartiesRecord> casePartiesRecord = casePartiesRecordMapper.selectByExample(queryExample);
        if (ObjectUtils.isEmpty(casePartiesRecord)) {
            throw new BusinessException("未找到当事人信息");
        }
        String partyIdentityCode = casePartiesRecord.get(0).getPartyIdentityCode();

        CaseDocumentSendinfoConfirmQueryDto queryDto = new CaseDocumentSendinfoConfirmQueryDto();
        queryDto.setPartyIdentityCode(partyIdentityCode);
        queryDto.setCaseDeptCode(deptCode);
        List<CaseDocumentSendinfoConfirm> sendInfoConfirmList = caseDocumentSendinfoConfirmMapper.getCaseDocumentSendinfoConfirmByPartyAndDept(queryDto);

        CaseDocumentSendinfoConfirmVo vo = new CaseDocumentSendinfoConfirmVo();
        vo.setHasSentAddressConfirmInfo(YesOrNoEnum.YES.getCode());
        vo.setIsNeedConfirmBeforeSend(YesOrNoEnum.NO.getCode());
        if (ObjectUtils.isEmpty(sendInfoConfirmList) || sendInfoConfirmList.size() == 0) {
            //未匹配到相关送达地址确认书信息
            vo.setHasSentAddressConfirmInfo(YesOrNoEnum.NO.getCode());
        } else {
            //fixme:目前只取一条（是否需要加状态，后期优化可考虑）
            CaseDocumentSendinfoConfirm record = sendInfoConfirmList.get(Constant.INTEGER_0);
            if (!ObjectUtils.isEmpty(record)) {
                BeanUtils.copyProperties(record, vo);
            }
            Integer status = record.getStatus();
            if (!Constant.INTEGER_1.equals(status)) {
                vo.setHasSentAddressConfirmInfo(YesOrNoEnum.NO.getCode());
                vo.setIsNeedConfirmBeforeSend(YesOrNoEnum.YES.getCode());
            }
        }
        vo.setIsNeedConfirmBeforeSendName(YesOrNoEnum.getValueByCode(vo.getIsNeedConfirmBeforeSend()));
        vo.setHasSentAddressConfirmInfoName(YesOrNoEnum.getValueByCode(vo.getHasSentAddressConfirmInfo()));*/
        return vo;
    }

    /**
     * 描述：获取送达详情
     *
     * @param dto {@link DocumentSentFlowDetailInfoDto}
     * @return {@link Result<  AppDocumentSentFlowDetailInfoVo  >}
     * @author zhengqiang
     * @date 2022/8/8
     * @since 1.3.2
     */
    @Override
    public AppDocumentSentFlowDetailInfoVo getDocumentSentFlowDetailInfo(DocumentSentFlowDetailInfoDto dto) {
        String caseId = dto.getCaseId();
        String documentId = dto.getDocumentId();
        String partyId = dto.getPartyId();
        AppDocumentSentFlowDetailInfoVo vo = new AppDocumentSentFlowDetailInfoVo();

        //查询文书记录
        CaseDocumentRecord record = caseDocumentRecordMapper.selectByPrimaryKey(documentId);
        if (ObjectUtils.isEmpty(record)) {
            throw new BusinessException("未找到文书信息");
        }
        //判断是否为多当事人文书
        String isPartiesDocument = YesOrNoEnum.NO.getCode();
        String docPartyId = record.getPartyId();
        if (!ObjectUtils.isEmpty(docPartyId) && docPartyId.contains(",")) {
            isPartiesDocument = YesOrNoEnum.YES.getCode();
            if (ObjectUtils.isEmpty(partyId)) {
                throw new BusinessException("多当事人合并处罚案件partyId不能为空");
            }
        }
        vo.setIsPartiesDocument(isPartiesDocument);
        vo.setPartyId(docPartyId);
        vo.setDocumentNumber(record.getDocumentNumber());


        //案件信息处理
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (caseMainInfo == null) {
            throw new BusinessException("未找到案件信息");
        }
        //1.将主表信息放入返回视图里面
        vo.setCaseId(caseMainInfo.getId());
        BeanUtils.copyProperties(caseMainInfo, vo);
        //2.办案人员信息
        Example handleExample = new Example(CaseHandlePersonRecord.class);
        handleExample.createCriteria().andEqualTo("caseId", caseId);
        handleExample.setOrderByClause("handle_person_type asc");
        List<CaseHandlePersonRecord> caseHandlePersonRecordList = caseHandlePersonRecordMapper.selectByExample(handleExample);
        if (caseHandlePersonRecordList.size() > 0) {
            vo.setCaseHandlingDeptInfo(caseHandlePersonRecordList.get(0).getHandleDeptName());
            vo.setCaseHandlePersonList(caseHandlePersonRecordList);
        } else {
            throw new BusinessException("未匹配到办案人员记录");
        }
        //3.组装当事人信息
        if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.equals(caseMainInfo.getCasePartiesReasonType())
                && caseMainInfo.getHandleType().equals(HandleTypeEnum.PART_PUNISH.getCode())) {
            //多当事人分别处罚时,根据partyId查询当事人信息
            Example queryExample = new Example(CasePartiesRecord.class);
            queryExample.createCriteria().andEqualTo("caseId", caseId)
                    .andEqualTo("status", "1").andEqualTo("partyId", docPartyId);
            List<CasePartiesRecord> casePartiesRecord = casePartiesRecordMapper.selectByExample(queryExample);
            if (ObjectUtils.isEmpty(casePartiesRecord)) {
                throw new BusinessException("未找到当事人信息");
            }
            vo.setPartyType(casePartiesRecord.get(0).getPartyType());
            vo.setPartyTypeName(PartyTypeEnum.getValueByCode(casePartiesRecord.get(0).getPartyType()));
            vo.setPartyShowName(casePartiesRecord.get(0).getPartyName());

        } else {
            List<CasePartiesRecordVo> casePartiesInfoList = casePartiesRecordService.getCasePartiesInfo(vo.getCaseId());
            CasePartiesRecordVo theFirstPartyInfo = casePartiesInfoList.get(Constant.INTEGER_0);
            String partyShowName = theFirstPartyInfo.getPartyName();
            //多当事人合并处罚对当事人名称进行处理
            if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.equals(caseMainInfo.getCasePartiesReasonType())
                    && caseMainInfo.getHandleType().equals(HandleTypeEnum.MERGE_PUNISH.getCode())) {
                int partyNum = casePartiesInfoList.size();
                if(partyNum > 1){
                    partyShowName += "等"+partyNum+"个";
                }
            }
            vo.setPartyType(theFirstPartyInfo.getPartyType());
            vo.setPartyTypeName(PartyTypeEnum.getValueByCode(theFirstPartyInfo.getPartyType()));
            vo.setPartyShowName(partyShowName);
        }

        //快办流程设置为普通程序
        if (CaseTypeEnum.SIMPLE_QUICK.getCode().equals(vo.getCaseType())) {
            vo.setCaseType(CaseTypeEnum.NORMAL_PROCEDURE.getDes());
        } else {
            vo.setCaseType(CaseTypeEnum.getValueByCode(vo.getCaseType()));
        }

        //4. 案由
        Example example = new Example(CaseReasonMainRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status","1");
        List<CaseReasonMainRecord> caseReasonMainRecordList = caseReasonMainRecordMapper.selectByExample(example);
        if (ObjectUtils.isEmpty(caseReasonMainRecordList) || caseReasonMainRecordList.size() == 0) {
            throw new BusinessException("未匹配到案件案由记录");
        }
        //多案由处理
        String showCaseReasonName = caseReasonMainRecordList.stream().map(reasonRecord -> reasonRecord.getCaseReasonName()).collect(Collectors.joining(";"));
        String showCaseReasonCode = caseReasonMainRecordList.stream().map(reasonRecord -> reasonRecord.getCaseReasonCode()).collect(Collectors.joining(";"));
        vo.setCaseReasonName(showCaseReasonName);
        vo.setCaseReasonCode(showCaseReasonCode);

        //组装文书信息
        BeanUtils.copyProperties(record, vo);
        vo.setSendStatusId(record.getDocumentSentStatus());
        vo.setSendStatusName(DocumentStatusEnum.getValueByCode(record.getDocumentSentStatus()));
        if(vo.getSentDeadline()!=null){
            Date date = Date.from(vo.getSentDeadline().atStartOfDay(ZoneId.systemDefault()).toInstant());
            String time = BaseUtil.calTime(new Date(), date, "true");
            vo.setRemaining(time);
        }


        //送达信息处理
        Example sendExample = new Example(DocumentSendRecord.class);
        Example.Criteria criteria = sendExample.createCriteria();
        criteria.andEqualTo("caseId", caseId).andEqualTo("isDelete", "0")
                .andEqualTo("documentId", documentId);
        if (!ObjectUtil.isEmpty(partyId)) {
            criteria.andEqualTo("partyId", partyId);
        }
        sendExample.orderBy("sendTime").desc();
        List<DocumentSendRecord> sendList = documentSendRecordMapper.selectByExample(sendExample);
        if (!ObjectUtils.isEmpty(sendList)) {
            DocumentSendRecord docSend = sendList.get(0);
            DocumentSentRegisterInfoRequest request = new DocumentSentRegisterInfoRequest();
            request.setCaseId(caseId);
            request.setDocumentId(documentId);
            request.setPartyId(partyId);
            request.setSentWay(docSend.getSentWay());
            Result<JSONObject> sentRegisterResult = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_DOCUMENT_SENT_REGISTER_INFO, request);
            DocumentSentRegisterVo sentRegisterInfo = JSONObject.parseObject(sentRegisterResult.getData().toJSONString(), DocumentSentRegisterVo.class);
            vo.setDocumentSentRegisterInfo(sentRegisterInfo);
        }

        //根据文书目录编码获取文书配置信息
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo
                = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(record.getDocumentCatalogCode());
        if (ObjectUtils.isEmpty(configBusiParamDocumentInfo)) {
            throw new com.icinfo.cloud.provider.common.exception.BusinessException("未匹配到文书配置信息-documentCatalogCode：" + record.getDocumentCatalogCode());
        }
        //设置文书相关配置属性
        vo.setIsConfirm(configBusiParamDocumentInfo.getIsConfirm());
        vo.setIsReceipt(configBusiParamDocumentInfo.getIsReceipt());
        vo.setIsElecSend(configBusiParamDocumentInfo.getIsElecSend());

        //送达回证逻辑处理
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        ConfigBusiParamDocumentInfo sdhzConfig = configBusiParamDocumentInfoService.getSDHZDetailBySentDocumentCatalogCode(record.getDocumentCatalogCode());
        String sentReceiptPrintDocumentCatalogCode = sdhzConfig.getDocumentCatalogCode();
        /*String sentReceiptPrintDocumentCatalogCode = Constant.TZ_KIND_CODE_RELATED_SENT_RECEIPT_DOCUMENT_CATALOG_CODE_MAP.get(documentKindCode);
        if (Constant.QS_BUSI_PARAM_ID.equals(configBusiParamDocumentInfo.getBusiParamId())) {
            sentReceiptPrintDocumentCatalogCode = Constant.QS_KIND_CODE_RELATED_SENT_RECEIPT_DOCUMENT_CATALOG_CODE_MAP.get(documentKindCode);
        }*/
        if (ObjectUtils.isEmpty(sentReceiptPrintDocumentCatalogCode)) {
            throw new com.icinfo.cloud.provider.common.exception.BusinessException("未匹配到送达文书对应送达回证文书目录编码");
        }

        //默认标记未生成送达回证
        vo.setIsSentReceiptCreated(YesOrNoEnum.NO.getCode());
        //获取送达回证文书记录信息
        CaseDocumentRecordDto caseDocumentRecordDto = new CaseDocumentRecordDto();
        caseDocumentRecordDto.setCaseId(caseId);
        caseDocumentRecordDto.setDocumentCatalogCode(sentReceiptPrintDocumentCatalogCode);
        caseDocumentRecordDto.setPartyId(partyId);
        Result<JSONObject> documentRecordResult = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_CASE_DOCUMENT_RECORD, caseDocumentRecordDto);
        if(!ObjectUtils.isEmpty(documentRecordResult)){
            int code = documentRecordResult.getCode();
            if(HttpStatus.HTTP_OK == code && !ObjectUtils.isEmpty(documentRecordResult.getData())){
                CaseDocumentRecord caseDocumentRecordReceipt = JSONObject.parseObject(documentRecordResult.getData().toJSONString(), CaseDocumentRecord.class);
                String sentReceiptPdfUrl = caseDocumentRecordReceipt.getDocumentUrl();
                if (!ObjectUtils.isEmpty(caseDocumentRecordReceipt.getDocumentUrlAfterSign())) {
                    sentReceiptPdfUrl = caseDocumentRecordReceipt.getDocumentUrlAfterSign();
                } else if (!ObjectUtils.isEmpty(caseDocumentRecordReceipt.getDocumentUrlAfterSeal())) {
                    sentReceiptPdfUrl = caseDocumentRecordReceipt.getDocumentUrlAfterSeal();
                }
                vo.setSentReceiptPdfUrl(sentReceiptPdfUrl);
                vo.setSentReceiptPrintDocumentCatalogCode(caseDocumentRecordReceipt.getDocumentCatalogCode());
                //标记已生成送达回证
                vo.setIsSentReceiptCreated(YesOrNoEnum.YES.getCode());
            } else {
                log.error("GET_CASE_DOCUMENT_RECORD请求异常" + documentRecordResult.getMessage());
            }
        }

        //设置送达流程处理
        if (!ObjectUtils.isEmpty(sendList)) {
            List<DocumentSentFlowInfoVo> sentFlowInfoVos = new ArrayList<>();
            sendList.forEach(sendRecord -> {
                DocumentSentFlowInfoVo documentSentFlowInfoVo = new DocumentSentFlowInfoVo();
                BeanUtils.copyProperties(sendRecord, documentSentFlowInfoVo);
                documentSentFlowInfoVo.setReceiverTypeName(SentRegisterReceiverTypeEnum.getValueByCode(sendRecord.getReceiverType()));
                documentSentFlowInfoVo.setSentWayName(SendWayEnum.getValueByCode(sendRecord.getSentWay()));
                documentSentFlowInfoVo.setOperateUserId(sendRecord.getSenderId());
                documentSentFlowInfoVo.setOperateUserName(sendRecord.getSenderRealName());
                documentSentFlowInfoVo.setOperateTime(sendRecord.getCreateTime());
                documentSentFlowInfoVo.setTitleShowTime(sendRecord.getSentTime());
                //送达回证pdf
                documentSentFlowInfoVo.setOperateUserPhotoUrl(vo.getSentReceiptPdfUrl());
            });
            vo.setDocumentSentFlowInfoList(sentFlowInfoVos);
        }

        return vo;
    }


    /**
     * 【V1.3.2】描述：保存签字捺印文书信息
     *
     * @param saveDto {@link AppDocumentSignAssembleInfoDto}
     * @return {@link Result<String>} 操作结果
     * @author xiangyuyu
     * @date 2022/8/8
     * @since 1.3.2
     */
    @Override
    public Result<String> saveDocumentSignInfo(AppDocumentSignAssembleInfoDto saveDto) {
        /*
            step1:重新生成签字捺印后的文书
            step2:标记文书【已确认（已送达）】
         */
        String documentId = saveDto.getDocumentId();
        String sentWay = saveDto.getSendWay();
        String realPlaceSentType = saveDto.getRealPlaceSentType();
        //如果是移动端+当场送达+源文件送达 需要进行一次"待确认"标记
        RealPlaceSentInfoSaveDto realPlaceSentInfoSaveDto = new RealPlaceSentInfoSaveDto();
        realPlaceSentInfoSaveDto.setDocumentId(documentId);
        //现场送达方式（1-原件签收/2-送达回证）
        realPlaceSentInfoSaveDto.setRealPlaceSentType(realPlaceSentType);
        realPlaceSentInfoSaveDto.setPartyId(saveDto.getPartyId());
        realPlaceSentInfoSaveDto.setDataSource(ApiVisitDataSourceEnum.PUNISH_MOBILE.getId());
        realPlaceSentInfoSaveDto.setSentWay(sentWay);
        if(RealPlaceSentTypeEnum.YJQS.getCode().equals(realPlaceSentType) && SendWayEnum.LOCAL_MSG.getCode().equals(sentWay)){
            //现场送达状态（0-待确认/1-已确认/2-取消）
            realPlaceSentInfoSaveDto.setRealPlaceSentStatus(Constant.STRING_0);
            signRealPlaceSentInfo(realPlaceSentInfoSaveDto);
        }

        String caseId = saveDto.getCaseId();
        String partyId = saveDto.getPartyId();
        //step1:重新生成签字捺印后的文书
        //获取文书信息
        CaseDocumentRecordVo caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecordInfo(documentId);
        String documentCatalogCode = caseDocumentRecord.getDocumentCatalogCode();
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo
                = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        if(YesOrNoEnum.YES.getCode().equals(saveDto.getIsSignSentReceipt())){
            //获取送达回证的文书目录编码
            //送达回证
            ConfigBusiParamDocumentInfo sdhzConfig = configBusiParamDocumentInfoService.getSDHZDetailBySentDocumentCatalogCode(documentCatalogCode);
            String sentReceiptPrintDocumentCatalogCode = sdhzConfig.getDocumentCatalogCode();
            /*String sentReceiptPrintDocumentCatalogCode = Constant.TZ_KIND_CODE_RELATED_SENT_RECEIPT_DOCUMENT_CATALOG_CODE_MAP.get(documentKindCode);
            if (Constant.QS_BUSI_PARAM_ID.equals(configBusiParamDocumentInfo.getBusiParamId())) {
                sentReceiptPrintDocumentCatalogCode = Constant.QS_KIND_CODE_RELATED_SENT_RECEIPT_DOCUMENT_CATALOG_CODE_MAP.get(documentKindCode);
            }*/
            if (ObjectUtils.isEmpty(sentReceiptPrintDocumentCatalogCode)) {
                return Result.error("未匹配到送达文书对应送达回证文书目录编码配置信息");
            }
            documentCatalogCode = sentReceiptPrintDocumentCatalogCode;
            //获取送达回证文书记录信息
            CaseDocumentRecordDto caseDocumentRecordDto = new CaseDocumentRecordDto();
            caseDocumentRecordDto.setCaseId(caseId);
            caseDocumentRecordDto.setDocumentCatalogCode(sentReceiptPrintDocumentCatalogCode);
            caseDocumentRecordDto.setPartyId(partyId);
            Result<JSONObject> documentRecordResult = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_CASE_DOCUMENT_RECORD, caseDocumentRecordDto);
            if(!ObjectUtils.isEmpty(documentRecordResult)){
                int code = documentRecordResult.getCode();
                if(HttpStatus.HTTP_OK == code){
                    CaseDocumentRecord record = JSONObject.parseObject(documentRecordResult.getData().toJSONString(), CaseDocumentRecord.class);
                    caseDocumentRecord = new CaseDocumentRecordVo();
                    BeanUtils.copyProperties(record,caseDocumentRecord);
                } else {
                    return Result.error(documentRecordResult.getMessage());
                }
            } else {
                return Result.error("未匹配到送达回证的文书信息");
            }
        }
        if (Constant.STRING_KIND_CODE_SDDZQRS.equals(documentKindCode)) {
            //送达地址确认书确认时更新送达地址确认书表的状态为1
            Example updateExample = new Example(CaseDocumentSendinfoConfirm.class);
            updateExample.createCriteria().andEqualTo("caseId", caseDocumentRecord.getCaseId()).andEqualTo("partyId", caseDocumentRecord.getPartyId());
            CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm = new CaseDocumentSendinfoConfirm();
            caseDocumentSendinfoConfirm.setStatus(Constant.INTEGER_1);
            caseDocumentSendinfoConfirmMapper.updateByExampleSelective(caseDocumentSendinfoConfirm, updateExample);
        }

        JSONObject documentContentJson = JSON.parseObject(caseDocumentRecord.getDocumentContent());
//        documentContentJson.put("QM", !ObjectUtils.isEmpty(saveDto.getSignFile()) ? saveDto.getSignFile(): "");
//        documentContentJson.put("NY", !ObjectUtils.isEmpty(saveDto.getFingerprint()) ? saveDto.getFingerprint(): "");
        //签名base64优化成地址 20230522
        String base64Str = ImageUtil.overlapImage(saveDto.getSignFile(), saveDto.getFingerprint());
        String ossUrl = appCaseBeforeDocumentRecordService.base64ToOssUrl(base64Str);
        documentContentJson.put("signFingerprintPic", ossUrl);
        documentContentJson.put("signFingerprintDate", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
        if (YesOrNoEnum.YES.getCode().equals(saveDto.getIsSignSentReceipt())) {
            documentContentJson.put("SDHZ_SJR_QM", !ObjectUtils.isEmpty(saveDto.getSignFile()) ? saveDto.getSignFile() : "");
            documentContentJson.put("signFingerprintPic", !ObjectUtils.isEmpty(saveDto.getFingerprint()) ? saveDto.getFingerprint() : "");
            documentContentJson.put("SDHZ_JZRQMSJ", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
        }

        String documentContent = documentContentJson.toJSONString();

        // 重新生成文书
        Map<String, Object> jsonObject = JSON.parseObject(documentContent);
        TemplateCodeInfoDto dto = new TemplateCodeInfoDto(documentCatalogCode,caseId,jsonObject);
        Result<String> templateCodeResult = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_TEMPLATE_CODE_BY_DOCUMENT_CATALOG_CODE, dto);
        int code = templateCodeResult.getCode();
        String templateCode;
        if(HttpStatus.HTTP_OK == code ){
            templateCode = templateCodeResult.getData();
        } else {
            return Result.error(templateCodeResult.getMessage());
        }
        FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
        pdfRequest.setTemplateCode(templateCode);
        pdfRequest.setParamMap(jsonObject);
        pdfRequest.setIsGeneratePcDoc(YesOrNoEnum.YES.getCode());
        //fixme 后期统一调用pc端接口
        Map<String, String> unSealPdfUrl = appCaseBeforeDocumentRecordService.getConvertedPdfUrl(pdfRequest);
        // 签字捺印
        /*String pdfSealUrl ="";
        if (Constant.STRING_1.equals(detailByDocumentCatalogCode.getIsDeptSign())){
            FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
            queryDto.setFileBase64(unSealPdfUrl.get("fileBase64"));
            pdfSealUrl = appCaseBeforeDocumentRecordService.dealFileSeal(queryDto);
        }else {
            pdfSealUrl=unSealPdfUrl.get("fileUrl");
        }*/
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseDocumentRecord.getCaseId());
        SysDepartParam sysDepartParam= sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());

        FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
        queryDto.setFileBase64(unSealPdfUrl.get("fileBase64"));
        queryDto.setUniscid(sysDepartParam.getUnicode());
        queryDto.setDeptCode(caseMainInfo.getCaseDeptCode());
        String pdfSealUrl = appCaseBeforeDocumentRecordService.dealFileSeal(queryDto);

        //保存文书签字捺印字段
        CaseDocumentRecord sdhzCaseDocumentRecord = new CaseDocumentRecord();
        sdhzCaseDocumentRecord.setId(caseDocumentRecord.getId());
        sdhzCaseDocumentRecord.setDocumentUrlAfterSign(pdfSealUrl);
        caseDocumentRecordMapper.updateByPrimaryKeySelective(sdhzCaseDocumentRecord);

        //step2:标记文书【已确认（已送达）】
        //标记
        realPlaceSentInfoSaveDto.setRealPlaceSentStatus(Constant.STRING_1);
        Result<String> result = signRealPlaceSentInfo(realPlaceSentInfoSaveDto);
        if (!ObjectUtils.isEmpty(result)) {
            if (HttpStatus.HTTP_OK == result.getCode()) {
                return Result.success(Constant.STRING_OPERATE_SUCCESS);
            } else {
                return Result.error(Constant.STRING_OPERATE_FAIL + ":" + result.getMessage());
            }
        }
        return Result.error(Constant.STRING_OPERATE_FAIL);
    }

    /**
     * 【V1.3.2】描述：获取送达表单信息
     *
     * @param dto {@link SentFormInfoDto}
     * @return {@link Result<  SentFormInfoVo  >} 送达表单信息
     * @author xiangyuyu
     * @date 2022/8/8
     * @since 1.3.2
     */
    @Override
    public SentFormInfoVo getSentFormInfo(SentFormInfoDto dto) {
        String partyId = dto.getPartyId();
        String caseId = dto.getCaseId();
        String documentId = dto.getDocumentId();

        DocumentSentRegisterInfoRequest request = new DocumentSentRegisterInfoRequest();
        request.setCaseId(caseId);
        request.setDocumentId(documentId);
        request.setPartyId(partyId);
        request.setSentWay(dto.getSentWay());
        request.setDataSource(ApiVisitDataSourceEnum.PUNISH_MOBILE.getId());
        Result<JSONObject> sentRegisterResult = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_DOCUMENT_SENT_REGISTER_INFO, request);
        DocumentSentRegisterVo sentRegisterInfo = JSONObject.parseObject(sentRegisterResult.getData().toJSONString(), DocumentSentRegisterVo.class);
        SentFormInfoVo vo = new SentFormInfoVo();
        if (!ObjectUtils.isEmpty(sentRegisterInfo)) {
            BeanUtils.copyProperties(sentRegisterInfo, vo);
        }
        //查询文书目录编码
        CaseDocumentRecord record = caseDocumentRecordMapper.selectByPrimaryKey(documentId);
        if (ObjectUtils.isEmpty(record)) {
            throw new BusinessException("文书记录不存在! documentId: " + documentId);
        }
        vo.setDocumentCatalogCode(record.getDocumentCatalogCode());

        return vo;
    }

    /**
     * 描述： 获取多当事人文书送达详情
     *
     * @author: zhengqiang
     * @date: 2022/8/11
     * @param: queryDto
     * @return {@link CasePartiesDocSendInfoVo}
     **/
    @Override
    public CasePartiesDocSendInfoVo getPartiesDocSendInfo(DocumentSendRecordByPartiesQueryDto queryDto) {
        String caseId = queryDto.getCaseId();
        String documentId = queryDto.getDocumentId();

        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (caseMainInfo == null) {
            throw new BusinessException("未找到案件信息");
        }
        CasePartiesDocSendInfoVo vo = new CasePartiesDocSendInfoVo();
        //1.将主表信息放入返回视图里面
        vo.setCaseId(caseMainInfo.getId());
        BeanUtils.copyProperties(caseMainInfo, vo);
        //2.办案人员信息
        Example handleExample = new Example(CaseHandlePersonRecord.class);
        handleExample.createCriteria().andEqualTo("caseId", caseId);
        handleExample.setOrderByClause("handle_person_type asc");
        List<CaseHandlePersonRecord> caseHandlePersonRecordList = caseHandlePersonRecordMapper.selectByExample(handleExample);
        if (caseHandlePersonRecordList.size() > 0) {
            vo.setCaseHandlingDeptInfo(caseHandlePersonRecordList.get(0).getHandleDeptName());
            vo.setCaseHandlePersonList(caseHandlePersonRecordList);
        } else {
            throw new BusinessException("未匹配到办案人员记录");
        }
        //3.获取当事人信息
        List<CasePartiesRecordVo> casePartiesInfoList = casePartiesRecordService.getCasePartiesInfo(vo.getCaseId());
        CasePartiesRecordVo theFirstPartyInfo = casePartiesInfoList.get(Constant.INTEGER_0);
        String partyShowName = theFirstPartyInfo.getPartyName();
        //多当事人合并处罚对当事人名称进行处理
        if (caseMainInfo.getHandleType().equals(HandleTypeEnum.MERGE_PUNISH.getCode())) {
            int partyNum = casePartiesInfoList.size();
            if(partyNum > 1){
                partyShowName += "等"+partyNum+"个";
            }
        }
        vo.setPartyShowName(partyShowName);
        //vo.setPartyType(theFirstPartyInfo.getPartyType());

        //快办流程设置为普通程序
        if (CaseTypeEnum.SIMPLE_QUICK.getCode().equals(vo.getCaseType())) {
            vo.setCaseType(CaseTypeEnum.NORMAL_PROCEDURE.getDes());
        } else {
            vo.setCaseType(CaseTypeEnum.getValueByCode(vo.getCaseType()));
        }

        //4. 案由
        Example example = new Example(CaseReasonMainRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status","1");
        List<CaseReasonMainRecord> caseReasonMainRecordList = caseReasonMainRecordMapper.selectByExample(example);
        if (ObjectUtils.isEmpty(caseReasonMainRecordList) || caseReasonMainRecordList.size() == 0) {
            throw new BusinessException("未匹配到案件案由记录");
        }
        //多案由处理
        String showCaseReasonName = caseReasonMainRecordList.stream().map(record -> record.getCaseReasonName()).collect(Collectors.joining(";"));
        String showCaseReasonCode = caseReasonMainRecordList.stream().map(record -> record.getCaseReasonCode()).collect(Collectors.joining(";"));
        vo.setCaseReasonName(showCaseReasonName);
        vo.setCaseReasonCode(showCaseReasonCode);

        //组装文书信息
        CaseDocumentRecord record = caseDocumentRecordMapper.selectByPrimaryKey(documentId);
        if (ObjectUtils.isEmpty(record)) {
            throw new BusinessException("未找到文书信息");
        }
        BeanUtils.copyProperties(record, vo);
        vo.setSendStatusId(record.getDocumentSentStatus());
        vo.setSendStatusName(DocumentStatusEnum.getValueByCode(record.getDocumentSentStatus()));
        //设置文书预览地址
        String documentUrl = record.getDocumentUrl();
        if (!ObjectUtils.isEmpty(record.getDocumentUrlAfterSign())) {
            documentUrl = record.getDocumentUrlAfterSign();
        } else if (!ObjectUtils.isEmpty(record.getDocumentUrlAfterSeal())) {
            documentUrl = record.getDocumentUrlAfterSeal();
        }
        vo.setDocumentUrl(documentUrl);
        if(vo.getSentDeadline()!=null){
            Date date = Date.from(vo.getSentDeadline().atStartOfDay(ZoneId.systemDefault()).toInstant());
            String time = BaseUtil.calTime(new Date(), date, "true");
            vo.setRemaining(time);
        }

        if (!ObjectUtils.isEmpty(documentId)) {
            //调用pc端接口获取多当事人送达信息
            Result result = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_DOCUMENT_SEND_RECORD_BY_PARTIES, queryDto);
            if (!ObjectUtils.isEmpty(result) && HttpStatus.HTTP_OK == result.getCode()) {
                List<DocumentSendRecordByPartiesVo> list = JSONArray.parseArray(JSONArray.toJSONString(result.getData()), DocumentSendRecordByPartiesVo.class);
                vo.setSendRecordByParties(list);
            }
        }

        return vo;
    }
}
